<template><u-navbar :autoBack="true" title="更换手机号"></u-navbar>
<view class="wrap">
    <view class="remind-text">更换手机号</view>
    <view class="tip">更换后需使用新手机号重新登录</view>
    <u-form class="form" :model="model" :rules="rules" ref="uForm" labelPosition="top">
        <u-form-item label="当前手机号" label-width="150" :borderBottom="true">
            {{currentPhone}}
        </u-form-item>
        <u-form-item label="新手机号" prop="newPhone" label-width="150" :borderBottom="true">
            <u-input v-model="model.newPhone" placeholder="请输入新手机号" border="none" type="number"
                maxlength="11"></u-input>
        </u-form-item>
        <u-form-item label="验证码" prop="verifyCode" label-width="150" :borderBottom="true">
            <view class="verify-code-wrapper">
                <u-input v-model="model.verifyCode" placeholder="请输入验证码" border="none" type="number"
                    maxlength="4"></u-input>
                <u-button :disabled="countdown > 0" :loading="sending" @click="sendCode" type="primary" size="small"
                    :custom-style="{ marginLeft: '20rpx', width: '180rpx' }">
                    {{ countdown > 0 ? countdown + 's' : '获取验证码' }}
                </u-button>
            </view>
        </u-form-item>
    </u-form>
    <view class="info">
        <view class="dot"></view>
        <view>验证码将发送到新手机号，请确保手机号正确</view>
    </view>
    <view class="form-footer">
        <u-button class="btn" type="primary" @click="submit">提交</u-button>
    </view>
</view>
</template>
<script>
import baseApi from '@/apis/cloud/base.js';
import { useUserStore,useLoginStore } from "@/pinia-store/user.js"
import { mapStores } from 'pinia'
export default {
    data() {
        return {
            currentPhone: '',
            worker_id: null,
            sending: false,
            countdown: 0,
            countdownTimer: null,
            model: {
                newPhone: '',
                verifyCode: ''
            },
            rules: {
                newPhone: [{
                    required: true,
                    message: '请输入新手机号',
                    trigger: ['change', 'blur'],
                },
                {
                    pattern: /^1[3-9]\d{9}$/,
                    message: '请输入正确的手机号',
                    trigger: ['change', 'blur'],
                }
                ],
                verifyCode: [{
                    required: true,
                    message: '请输入验证码',
                    trigger: ['change', 'blur'],
                }],
            }
        };
    },
    onLoad(option) {
		this.userInfo = this.userStore.user;
        this.worker_id = this.userInfo.worker_id;
        this.currentPhone = this.userInfo.phone || '';
    },
	computed: {
		...mapStores(useUserStore, useLoginStore)
	},
    onUnload() {
        // 清除定时器
        if (this.countdownTimer) {
            clearInterval(this.countdownTimer);
        }
    },
    onReady() {
        this.$refs.uForm.setRules(this.rules);
    },
    methods: {
        // 发送验证码
        async sendCode() {
            // 先验证手机号格式
            if (!this.model.newPhone) {
                uni.$u.toast('请输入新手机号');
                return;
            }
            if (!/^1[3-9]\d{9}$/.test(this.model.newPhone)) {
                uni.$u.toast('请输入正确的手机号');
                return;
            }
            // 检查是否和当前手机号相同
            if (this.model.newPhone === this.currentPhone) {
                uni.$u.toast('新手机号不能与当前手机号相同');
                return;
            }

            this.sending = true;
            try {
                const res = await baseApi.sendSms({
                    send_phone: this.model.newPhone,
                    worker_phone: this.model.newPhone,
					type: "sms"
                });
                if (res.status == 1) {
                    uni.$u.toast('验证码发送成功');
                    // 开始倒计时
                    this.countdown = 60;
                    this.countdownTimer = setInterval(() => {
                        this.countdown--;
                        if (this.countdown <= 0) {
                            clearInterval(this.countdownTimer);
                            this.countdownTimer = null;
                        }
                    }, 1000);
                } else {
                    uni.$u.toast(res.msg || '验证码发送失败');
                }
            } catch (error) {
                uni.$u.toast('验证码发送失败，请稍后重试');
            } finally {
                this.sending = false;
            }
        },
        async submit() {
            var flag = false;
            await this.$refs.uForm.validate().then(res => {
                flag = true;
            }).catch(errors => {
                uni.$u.toast(errors[0].message)
            })
            if (flag) {
                // 检查是否和当前手机号相同
                if (this.model.newPhone === this.currentPhone) {
                    uni.$u.toast('新手机号不能与当前手机号相同');
                    return;
                }

                const res = await baseApi.updatePhone({
                    worker_id: this.userStore.user.worker_id,
                    new_phone: this.model.newPhone,
                    verify_code: this.model.verifyCode
                });
                if (res.status == 1) {
                    uni.showModal({
                        title: '提示',
                        content: "更换手机号成功，需重新登录",
                        showCancel: false,
                        success: () => {
                            uni.redirectTo({
                                url: '/pages/user/login'
                            });
                        }
                    });
                } else {
                    uni.showModal({
                        title: '提示',
                        content: res.msg || "更换手机号失败，请联系管理员",
                        showCancel: false
                    });
                }
            }
        }
    }
};
</script>
<style lang="scss">
.wrap {
    height: calc(100vh - 88rpx - var(--status-bar-height));
    padding: 0 30rpx;
    padding-top: calc(88rpx + var(--status-bar-height));
    overflow-y: scroll;
}

.u-form {
    //background: #fff;
}

.remind-text {
    font-size: 38rpx;
    font-weight: bold;
    margin-top: 60rpx;
    letter-spacing: 2rpx;
}

.tip {
    color: #aaa;
    font-size: 28rpx;
    padding: 20rpx 0;
    letter-spacing: 2rpx;
    margin-bottom: 40rpx;
}

.info {
    display: flex;
    align-items: center;
    color: #aaa;
    padding: 60rpx 0;
}

.dot {
    width: 12rpx;
    height: 12rpx;
    border-radius: 50%;
    background-color: #fa3534;
    margin-right: 20rpx;
    align-self: flex-start;
    margin-top: 12rpx;
}

.verify-code-wrapper {
    display: flex;
    align-items: center;
    width: 100%;
}

.form-footer {
    margin-top: 60rpx;
}

.btn {
    width: 100%;
}
</style>
